package com.duofan.gmall.auth.service.impl;

import com.duofan.gmall.auth.feign.ThirdPartyFeignService;
import com.duofan.gmall.auth.service.LoginService;
import com.duofan.gmall.auth.vo.UserRegVo;
import com.duofan.gmall.common.constant.AuthServerConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    ThirdPartyFeignService thirdPartyFeignService;
    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public int sendCode(String phone) {
        // TODO 接口防刷
        String cacheKey = AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone;
        String redisCode = redisTemplate.opsForValue().get(cacheKey);
        if(!StringUtils.isEmpty(redisCode)) {
            long l = Long.parseLong(redisCode.split("_")[1]);
            // 防止同一手机号在60s内再次发送验证码
            if(System.currentTimeMillis() - l < 60 * 1000) {
                return -1;
            }
        }
        // UUID生成验证码
        String code = UUID.randomUUID().toString().substring(0, 5);
        thirdPartyFeignService.sendCode(phone, code);
        // 保存验证码到redis
        // 键 -> code:sms:手机号 十分钟有效
        String cacheValue = code + "_" + System.currentTimeMillis();
        redisTemplate.opsForValue().set(cacheKey, cacheValue, 10, TimeUnit.MINUTES);
        return 0;
    }


    /**
     * 验证码校验
     */
    @Override
    public boolean checkCode(UserRegVo vo)  {
        String cacheKey = AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone();
        String cacheValue = redisTemplate.opsForValue().get(cacheKey);
        if(!StringUtils.isEmpty(cacheValue)) {
            String code = cacheValue.split("_")[0];
            if(!vo.getCode().equals(code)) {
                // 验证码验证通过,删除验证码
                redisTemplate.delete(cacheKey);
                return true;
            } else {
                // 验证码不匹配
                return false;
            }
        } else {
            // 验证码过期
            return false;
        }
    }
}
